/* eslint-disable */
import { IApi } from 'umi';
// import signale from 'signale';
import { join, resolve } from 'path';
import { readdirSync } from 'fs';

function getRoutes(type: string) {
  const dirs = readdirSync(join(__dirname, type));
  const routes = [];
  for (const dir of dirs) {
    if (dir.charAt(0) === '.') continue;
    routes.push({
      path: `/${type}/${dir}`,
      component: resolve(type, dir, 'src', 'index.tsx'),
    });
  }
  return routes;
}

// function getRoute() {
//   return {
//     path: '/',
//     component: join(process.env.BLOCK || '', 'src', 'index.tsx'),
//   };
// }

export default (api: IApi) => {
  const generateConfig = require('./_scripts/project-info');
  generateConfig();
  api.paths.absSrcPath = __dirname;
  api.paths.absPagesPath = resolve(__dirname, 'templates');

  const block = process.env.BLOCK || process.argv.slice(2)[1] || '';
  const isBlock = block.indexOf('blocks/') > -1 || block.indexOf('blocks\\') > -1;
  const blockPath = join(process.cwd(), `${block || '.'}`);
  let appRoutes: any[] = [];
  if (block) {
    api.paths.absPagesPath = resolve(__dirname, blockPath, 'src')
    appRoutes = [
      {
        path: '/',
        exact: false,
        component: resolve(__dirname, `src/layouts/${isBlock ? 'block' : 'template'}-layout`),
        routes: [
          {
            path: '/ued',
            component: '@hzero-front-ui/cfg/lib/pages'
          },
          {
            path: '/',
            component: resolve(blockPath, 'src/index.tsx'),
          },
        ],
      },
    ];
  } else {
    appRoutes = [
      {
        path: '/',
        component: resolve(__dirname, 'src/layouts/top-level'),
        routes: [
          { path: '/', exact: true, component: resolve(__dirname, 'src/pages/Home/index.tsx') },
          {
            path: '/ued',
            // component: '@hzero-front-ui/cfg/lib/pages'
            component: require.resolve(resolve(__dirname, 'src/layouts/template-layout-pure')),
            routes: [
              {
                path: '/ued',
                exact: true,
                component: '@hzero-front-ui/cfg/lib/pages'
              }
            ]
          },
          {
            path: '/blocks',
            name: 'Blocks',
            exact: false,
            key: 'blocks',
            component: require.resolve(resolve(__dirname, 'src/layouts/block-layout-pure')),
            routes: [
              { path: '/blocks', exact: true, component: resolve(__dirname, 'src/_components/Menu.tsx') },
              ...getRoutes('blocks')
            ]
          },
          {
            path: '/templates',
            exact: false,
            name: 'Templates',
            key: 'templates',
            component: require.resolve(resolve(__dirname, 'src/layouts/template-layout-pure')),
            routes: [
              { path: '/templates', exact: true, component: resolve(__dirname, 'src/_components/Menu.tsx') },
              ...getRoutes('templates')
            ]
          },
        ],
      },
    ];
  }

  api.modifyRoutes(routes => {
    return appRoutes;
  });
  const imports = [
    `${resolve(__dirname, 'global.modules.less')}?modules`,
    'choerodon-ui/dist/choerodon-ui.css',
    'choerodon-ui/dist/choerodon-ui-pro.css',
    `${resolve(__dirname, 'src', 'global.tsx')}`,
  ].map(source => ({ source }));

  api.addEntryImportsAhead(() => imports);

  // const errors: any[] = [];

  // api.chainWebpackConfig(config => config.devServer.contentBase(join(__dirname, 'dist')).end());
  // api._beforeServerWithApp(({ app }) => {
  //   if (process.env.MOCK !== 'none' && process.env.HTTP_MOCK !== 'none') {
  //     const {
  //       cwd,
  //       config,
  //       paths: { absPagesPath, absSrcPath },
  //     } = api;
  //     // console.log(cwd);process.exit();
  //     app.use(
  //       createMiddleware({
  //         cwd,
  //         config,
  //         errors,
  //         absPagesPath: cwd,
  //         absSrcPath,
  //         watch: !process.env.WATCH_FILES,
  //         onStart() {
  //           api.addBabelRegister([
  //             resolve(__dirname, '_scripts'),
  //             resolve(__dirname, 'templates'),
  //             resolve(__dirname, 'blocks'),
  //           ]);
  //         },
  //       }).middleware,
  //     );
  //   }
  // });

  // api.onDevCompileDone(() => {
  //   if (errors.length) {
  //     signale.error(`Mock file parse failed`);
  //     errors.forEach(e => {
  //       console.error(e.message);
  //     });
  //   }
  // });
};
